package com.khotyn.heresy.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.khotyn.heresy.bean.HeresyErrorMessage;
import com.khotyn.heresy.bean.UserDetail;
import com.khotyn.heresy.dao.UserDAO;
import com.khotyn.heresy.service.PasswordService;
import com.khotyn.heresy.util.KeywordFilter;
import com.khotyn.heresy.validator.UserDetailValidator;

/**
 * 用户编辑个人信息控制器 用户可以同时修改密码 URI:/editUserInfo.html
 * 
 * @author jinlingjie
 * 
 */
@Controller
@RequestMapping("/editUserInfo.html")
public class UserInfoEditController {
	@Autowired
	private UserDAO userDAO;

	@Autowired
	private PasswordService passwordService;

	/**
	 * @param userDAO the userDAO to set
	 */
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	/**
	 * 初始化编辑个人信息表单
	 * 
	 * @param session 用户会话
	 * @param userIDStr 用户id的字符串
	 * @param model 存放返回视图数据的模型
	 * @return 返回的视图名称
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String setupUserInfoForm(HttpSession session, @RequestParam(value = "userID", required = false) String userIDStr, ModelMap model) {
		// 未登录的用户
		Integer myID = (Integer) session.getAttribute("userID");
		if (userIDStr == null || myID == null) {
			HeresyErrorMessage message = new HeresyErrorMessage("您尚未登录请先登录", "请登录", "login.html");
			model.addAttribute("message", message);
			return "message";
		}

		// 非法的参数
		if (!KeywordFilter.isNumeric(userIDStr)) {
			HeresyErrorMessage message = new HeresyErrorMessage("非法的参数", "操作失败", "login.html");
			model.addAttribute("message", message);
			return "message";
		}

		// 用户不匹配
		if (Integer.parseInt(userIDStr) != myID) {
			HeresyErrorMessage message = new HeresyErrorMessage("您只能修改自己的信息", "操作失败", "user.html?userID=" + myID);
			model.addAttribute("message", message);
			return "message";
		}

		UserDetail userDetail = userDAO.selectUserByUserId(myID);
		model.addAttribute("userDetail", userDetail);
		return "userinfo";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String editUserInfo(@ModelAttribute("userDetail") UserDetail userDetail, BindingResult result, ModelMap model,
			@RequestParam(value = "oldPassword", required = false) String oldPassword, HttpServletRequest request, HttpSession session) {
		Integer myID = (Integer) session.getAttribute("userID");
		if (myID == null) {
			HeresyErrorMessage message = new HeresyErrorMessage("会话已经过期，请重新登录", "会话过期", "login.html");
			model.addAttribute("message", message);
			return "message";
		}

		if (userDetail.getUserID() == 0 && request.getParameter("userID") != null && request.getParameter("userID") != "") {
			userDetail.setUserID(Integer.parseInt(request.getParameter("userID")));
		}

		int initErrorCount = result.getErrorCount();
		// 使用验证器验证表单数据
		new UserDetailValidator().validate(userDetail, result);

		if (result.hasErrors() && (result.getErrorCount() > initErrorCount)) {
			return "userinfo";
		}

		// 用户需要同时修改密码
		if (!userDetail.getPassword().isEmpty() && oldPassword != null) {
			if (!passwordService.changePassword(oldPassword, userDetail)) {
				model.addAttribute("errorPasswordStr", "原密码错误，请重新输入");
				return "userinfo";
			}
		}

		userDAO.updateUser(userDetail);

		HeresyErrorMessage message = new HeresyErrorMessage("编辑个人信息成功，现在返回您的首页", "编辑成功", "user.html?userID=" + userDetail.getUserID());
		model.addAttribute("message", message);
		return "message";
	}

	/**
	 * 设置表单中日期的格式化方法
	 * 
	 * @param binder 用于绑定表单数据格式化方法
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

	/**
	 * @param passwordService the passwordService to set
	 */
	public void setPasswordService(PasswordService passwordService) {
		this.passwordService = passwordService;
	}
}
